import { _decorator, Component, find, Node, Tween, UIComponent, UITransform } from 'cc';
import { ICommandLifecycle } from './ICommandLifecycle';
import { IGuideData } from './IGuideData';
import { GuideEvents } from '../GuideEvents';
import { app } from 'db://assets/app/app';
const { ccclass, property } = _decorator;

@ccclass('BaseGuideCommand')
export abstract class BaseGuideCommand implements ICommandLifecycle {
    protected guideNode: Node;
    protected stepConfig: IGuideData;
    protected curTween: Tween;

    private _isExecuting: boolean = false;

    constructor(guideNode: Node, stepConfig: IGuideData) {
        this.guideNode = guideNode;
        this.stepConfig = stepConfig;
    }

    public async execute(): Promise<void> {
        if (this._isExecuting) return;

        try {
            this._isExecuting = true;
            this.onStart();

            await this.run();

            this.onComplete();
        }
        catch (error) {
            this.onError(error as Error);
        }
        finally {
            this._isExecuting = false;
        }
    }

    //抽象方法：由子类实现具体逻辑
    protected abstract run(): Promise<void>;

    onStart(): void {
        console.log("[Command] 开始执行");
        let targetNode = find(this.stepConfig.path);
        let worldPos = targetNode.getWorldPosition()
        let size = targetNode.getComponent(UITransform).contentSize.clone();
        app.manager.event.emit(GuideEvents.Updata_Guides, worldPos, size)
    }
    onProgress(progress: number): void {
        console.log(`[Command] 执行中，进度: ${progress}%`);
    }
    onComplete(): void {
        console.log("[Command] 执行完成");
    }
    onError(error: Error): void {
        console.error("[Command] 执行出错:", error.message);
    }

    public stopTween(): void {
        this.curTween?.stop()
    }
}


